<?php
class Zend_View_Helper_TreeMaker extends Zend_View_Helper_Abstract
{
	 const ADD    = 'add';
	 const EDIT   = 'edit';
	 const DELETE = 'delete';
//needs atrrs: parent_id, has_child, title, category_id - :(
//
	/**
	 * return str of tree of smth
	 * makes three additional action links(edit,delete,add)
	 * only children can be deleted
	 * @param array of Row objects $categories
	 * @param $strBlock
	 * @param $prevId
	 * @param $actionsLinks
	 * @param $actionsFlag
	 */

	public function treeMaker($categories, $strBlock = '', $prevId = 0, $actionsFlag = false){
		foreach($categories as $category)
		{
			if(is_null($category->parent_id) && $prevId == 0){
				$strBlock .= '<ul><li>'.$category->title.'</li>';
				if(!empty($actionsFlag)){
					$deleteFlag = ($category->has_child)?false:true;
					$strBlock .= $this->_makeEditeDeleteAddLinks($category->category_id, $deleteFlag);
				}
				reset($categories);
				$strBlock = $this->treeMaker($categories, $strBlock, $category->category_id, $actionsFlag);
				//output of the string
			}
			else if($category->parent_id == $prevId){
				$strBlock .= '<ul><li>'.$category->title.'</li>';
				if(!empty($actionsFlag)){
					$deleteFlag = ($category->has_child)?false:true;
					$strBlock .= $this->_makeEditeDeleteAddLinks($category->category_id, $deleteFlag);
				}
				if(!empty($category->has_child)){
					reset($categories);
					$strBlock = $this->treeMaker($categories, $strBlock, $category->category_id, $actionsFlag);
				}
				$strBlock .= '</ul>';
			}
		}
		return $strBlock.'</ul>';
	}

	private function _makeEditeDeleteAddLinks($id = '',$deleteFlag = true){
		$strEditeDeleteAddLinks = '<a href="';
		$strEditeDeleteAddLinks .= $this->view->url(array('action'=>self::ADD, 'id' => $id));
		$strEditeDeleteAddLinks .= '">'.self::ADD.'</a>';
		$strEditeDeleteAddLinks .= '<a href="';
		$strEditeDeleteAddLinks .= $this->view->url(array('action'=>self::EDIT, 'id' => $id));
		$strEditeDeleteAddLinks .= '">'.self::EDIT.'</a>';
		if(!empty($deleteFlag)){
			$strEditeDeleteAddLinks .= '<a href="';
			$strEditeDeleteAddLinks .= $this->view->url(array('action'=>self::DELETE, 'id' => $id));
			$strEditeDeleteAddLinks .= '">'.self::DELETE.'</a>';
		}else{
			$strEditeDeleteAddLinks .= self::DELETE;
		}
		return '<span id="category_action">'.$strEditeDeleteAddLinks.'</span>';
	}


}